import { toRaw, reactive, toRefs, inject } from 'vue'
import { useMessage } from 'naive-ui'
import type { configType, stateInter } from '@/types/hooks/addDia'
export function diaApi(config: configType) {
  const { apis, emit } = config
  const $clone = inject('$clone') as <T>(data: T) => T
  const state = reactive<stateInter>({
    dialogFormVisible: false,
    title: '',
    queryForm: {}
  })
  const toast = useMessage()
  if (config?.queryForm) {
    state.queryForm = $clone(config.queryForm)
  }

  const handleValidateClick = (e: MouseEvent) => {
    e.preventDefault()
    config.ruleForm.value?.validate((errors: any) => {
      if (!errors) {
        save()
      }
    })
  }

  const save = async () => {
    let params: any = toRaw(state.queryForm)
    if (config?.saveParams) {
      params = config.saveParams(params)
    }
    if (params?.id) {
      const { code, message } = await apis.doEdit.api(params)
      if (code !== 200) {
        toast.error(message)
        return
      }
      toast.success(apis.doEdit?.successText || '编辑成功')
    } else {
      const { code, message } = await apis.doAdd.api(params)
      if (code !== 200) {
        toast.error(message)
        return
      }
      toast.success(apis.doAdd?.successText || '添加成功')
    }
    emit('success')
    close()
  }

  const open = (row: any) => {
    if (row) {
      state.title = row?.id ? '编辑' : '添加'
      state.queryForm = Object.assign({}, row)
    } else {
      state.title = '添加'
    }
    state.dialogFormVisible = true
    if (config?.showEdit) {
      config?.showEdit()
    }
  }

  const close = () => {
    if (config?.ruleForm) {
      config?.ruleForm.value.restoreValidation()
    }
    if (config.queryForm) {
      state.queryForm = $clone(config.queryForm)
    } else {
      state.queryForm = {}
    }
    if (config?.closeExtend) {
      config?.closeExtend()
    }
    state.dialogFormVisible = false
  }

  return {
    ...toRefs(state),
    open,
    close,
    handleValidateClick
  }
}
